package net.roseboy.classfinal.util;

import a.a.a.A;
import net.roseboy.classfinal.Const;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class AgentCreateUtil {
    public static void createAgent(String targetRoot){
        Map<String, byte[]> map = getClassFinalAgent();
        packageJar(map,new File(targetRoot).getAbsolutePath());
    }

    public static Map<String,byte[]> getClassFinalAgent() {
        Map<String,byte[]> map =new HashMap<>();
        List<String> thisJarPaths = new ArrayList<>();
        thisJarPaths.add(AgentCreateUtil.class.getProtectionDomain().getCodeSource().getLocation().getPath());
        //把本项目的class文件打包进去
        for (String thisJar : thisJarPaths) {

            File thisJarFile = new File(thisJar);
            if ( thisJar.endsWith(".jar")) {
                List<String> includeFiles = Arrays.asList(Const.CLASSFINAL_FILES);
                map.putAll(JarUtils.unZipToMap(thisJar,  includeFiles));
            }
            //本项目开发环境中未打包
            else if (thisJar.endsWith("/classes/")) {
                List<File> files = new ArrayList<>();
                IoUtils.listFile(files, new File(thisJar));
                for (File file : files) {

                    String className = file.getAbsolutePath().substring(thisJarFile.getAbsolutePath().length());
                    if (file.isDirectory()) {
                        map.put(className,null);
                    } else if (StrUtils.containsArray(file.getAbsolutePath(), Const.CLASSFINAL_FILES)) {
                        map.put(className,IoUtils.readFileToByte(file));
                    }

                }
            }
        }

        //把javaagent信息加入到MANIFEST.MF
        String preMain = "Premain-Class: " + A.class.getName();
        String[] texts = {};

        String str = StrUtils.insertStringArray(texts, preMain, "Main-Class:");
        map.put("META-INF/MANIFEST.MF",(str + "\r\n\r\n").getBytes(StandardCharsets.UTF_8));
        return map;
    }
    /**
     * 压缩成jar
     *
     * @return 打包后的jar绝对路径
     */
    private static String packageJar(Map<String, byte[]> map,String targetRoot) {
        String targetAgent = new File(targetRoot+"/"+"class-final-sunray-agent.jar").getAbsolutePath() ;
        String result2 = JarUtils.doJar(map, targetAgent);
        Log.debug("打包: " + targetAgent);
        System.out.println("打包: " + targetAgent);
        return result2;
    }
}
